var myModal;

function showModal(title) {
    $('#exampleModalLabel').text(title);
      
      // 显示弹窗
      myModal.show()
      
}


// 检查用户是否已登录
function checkAuth() {
    fetch('/api/check-auth/', {
        credentials: 'include'
    })
    .then(response => response.json())
    .then(data => {
        if (data.isAuthenticated) {
        } else {
            window.location.href = '/login.html';
        }
    });
}


function playAudio(file='/static/media/dingdong.wav') {
    try {
      // 创建音频上下文
      const AudioContext = window.AudioContext || window.webkitAudioContext;
      if (!AudioContext) {
        throw new Error('您的浏览器不支持Web Audio API');
        alert('您的浏览器不支持Web Audio API');
      }
      
      const audioCtx = new AudioContext();
      
      // 检查音频上下文状态（iOS可能需要恢复）
      if (audioCtx.state === 'suspended') {
        audioCtx.resume().then(() => {
          console.log('音频上下文已恢复');
        }).catch(e => {
          alert('无法启动音频: ' + e.message);
        });
      }
      
      fetch(file)
        .then(response => {
          if (!response.ok) {
            throw new Error('音频文件加载失败: ' + response.status);
          }
          return response.arrayBuffer();
        })
        .then(arrayBuffer => audioCtx.decodeAudioData(arrayBuffer))
        .then(audioBuffer => {
          const source = audioCtx.createBufferSource();
          source.buffer = audioBuffer;
          source.connect(audioCtx.destination);
          source.start(0);
          
          // 播放成功可以添加回调
          console.log('音频播放开始');
        })
        .catch(e => {
          alert('音频播放错误: ' + e.message);
          console.error('音频播放错误:', e);
        });
    } catch (e) {
      alert('音频初始化错误: ' + e.message);
      console.error('音频初始化错误:', e);
    }
  }

var curNum = null; 

function loadAllTrend() {
    const savedValues = JSON.parse(localStorage.getItem('alertValues') || '[]');
    const choices = savedValues.join(',');
    const url = '/api/cache_ffk3_mult_conn';
    $('#dataTable').bootstrapTable('refresh', {url: url});
}



function startAllTrend() {
    $('#exampleModalBody').html(`
        <table id="dataTable" class="" classList=""></table>
    `);

    myModal = new bootstrap.Modal(document.getElementById('exampleModal'))
    
    var DT = 'ds';
    var TRANS, TRANS_DS;
    TRANS = TRANS_DS = {
        0: '双',
        1: '单'
    }
    var TRANS_DX = {
        0: '小',
        1: '大'
    }
    const savedValues = JSON.parse(localStorage.getItem('alertValues') || '[]');
    const choices = savedValues.join(',');
    $('#dataTable').bootstrapTable({
        responseHandler: function (res, jqXHR) {
            res = res.rows;
            if (res.length && !myModal._isShown && res[0]['num'] != curNum) {
                $('#settingsModal').modal('hide');
                showModal("全局通知");
                playAudio('/static/media/reminder.mp3');
            }
            if (res.length == 0) {
                myModal.hide()
            }
            for (var row of res) {
                row['next_num'] = row.num + 1;

                if (row['type'] == 'ds') {
                    TRANS = TRANS_DS
                } else {
                    TRANS = TRANS_DX
                }
                
                ['predict', 'value', 'next_predict'].map(function (x) {
                    row[x] = TRANS[row[x]];
                });

                
                if (row['last']) {
                    col = 'success'
                } else {
                    col = 'danger'
                }

                row['conn'] =  `<span class="badge fs-6 bg-`+ col + `">` + row['conn'] + `</span>`;

                if (row['now']) {
                    row['num_desc'] = `<span class="badge bg-warning">` + row['num'] + `</span>`;
                    row['next_num'] = `<span class="badge bg-warning">` + row['next_num'] + `</span>`;
                } else {
                    row['num_desc'] = row['num'];
                }

                if (row['now'] && row['num'] != curNum) {
                    curNum = row['num'];
                }
            }
            return res;
        },
        url:  '/api/ffk3_mult_conn?cur=true&type=all&choices=' + choices + '&page=all',
        toolbar: '#toolbar',
        columns: [{
            field: 'page',
            title: '页面',
        }, {
            field: 'group',
            title: '小组',
        }, {
            field: 'num',
            title: '期号',
            visible: false,
        }, {
            field: 'num_desc',
            title: '期号',
        }, {
            field: 'predict',
            title: '预测'
        }, {
            field: 'value',
            title: '开盘'
        }, {
            field: 'next_num',
            title: '下期'
        }, {
            field: 'next_predict',
            title: '预测'
        }, {
            field: 'conn',
            title: '连续',
            sortable: true,
        }],
        filterControl: true,
         sortName: 'num', 
         sortOrder: 'desc', 
    });
    setInterval(loadAllTrend, 5000);
}

// startAllTrend();




        
    // 保存设置
    function saveSettings() {
        const checkedValues = [];
        document.querySelectorAll('.form-check-input:checked').forEach(checkbox => {
            checkedValues.push(checkbox.value);
        });
        
        // 这里可以添加保存到本地存储或发送到服务器的代码
        localStorage.setItem('alertValues', JSON.stringify(checkedValues));
        
        $('#settingsModal').modal('hide');
    }
    
    // 加载保存的设置
    function loadSettings() {
        const savedValues = JSON.parse(localStorage.getItem('alertValues') || '[]');
        savedValues.forEach(value => {
            const checkbox = document.getElementById(`alertValue${value}`);
            if (checkbox) {
                checkbox.checked = true;
            }
        });
    }
    